from rest_framework.serializers import ModelSerializer
from django.utils import timezone
from .models import Qusetions,Answer, Label
from users.models import User
from rest_framework import serializers


class LabelSerializer(ModelSerializer):

    class Meta:
        model = Label
        fields = '__all__'


class UserSerializer(ModelSerializer):
    class Meta:
        model= User
        fields = ('username',)


class AskSerializer(ModelSerializer):
    respondent = UserSerializer()
    class Meta:
        model = Answer
        fields = ('update_time', 'content', 'respondent', 'question')



class QuestionsSerializer(ModelSerializer):

    # answer_set = AskSerializer(many=True)
    # answer_set = serializers.PrimaryKeyRelatedField(read_only=True, many=True)

    # answer_set = AskSerializer(many=True)
    author = UserSerializer()
    subs = AskSerializer(many=True)
    label = LabelSerializer()
    class Meta:

        model = Qusetions
        fields = ('id', 'title', 'content', 'label', 'browse', 'author','like_count', 'create_time','update_time', 'subs' )
        # fields = '__all__'

class QuestionsAnswerSerializer(ModelSerializer):
    label = LabelSerializer()
    author = UserSerializer()
    class Meta:

        model = Qusetions
        fields = ('title', 'label', 'browse', 'author','like_count', 'create_time','update_time', 'content' )
        # fields = '__all__'



class SubmitSerializer(ModelSerializer):

    class Meta:
        model = Qusetions
        fields = ('id', 'title', 'author', 'label', 'content', 'create_time')
        extra_kwargs = {
            "id": {"read_only": True},
            "create_time": {"read_only": True}
        }

    def create(self, validated_data):
        title = validated_data['title']
        label = validated_data['label']
        content = validated_data['content']
        author = validated_data.get("author", None)
        # 获取用户对象  user
        # user = self.context['request'].user
        return super().create(validated_data)




